<template>
    <div>
        <!-- 搜索 -->
        <el-form :inline="true" :model="SelectedInfo" class="demo-form-inline" style="margin-top: 10px;">
            <el-form-item label="擅长领域名称：">
                <el-input v-model="SelectedInfo.name" style="width: 240px;" placeholder="请输入擅长领域的名称" clearable />
            </el-form-item>
            <el-button type="primary" @click="getSpecialty">搜索</el-button>
        </el-form>
        <el-button @click="toAdd" type="primary" icon="Plus" plain style="margin-bottom: 15px;">新增</el-button>
        <el-button type="danger" @click="handleBatchDelete" icon="Delete" plain style="margin-bottom: 15px;">批量删除</el-button>
        <!-- 表格 -->
        <el-table @selection-change="handleSelectionChange" :data="tableData" style="width: 100%">
            <el-table-column type="selection" width="100" align="center" />
            <el-table-column fixed prop="id" label="编号" width="150" align="center" />
            <el-table-column prop="name" label="擅长领域名称" width="400" align="center" />
            <el-table-column fixed="right" label="操作" min-width="400" align="center">
                <template #default="scope">
                    <el-button link @click="toEdit(scope.row)">修改</el-button>
                    <el-button link type="danger" @click="onDel(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 添加，编辑弹框 -->
        <el-dialog v-model="saveOrUpdateVisiable" :title="saveOrUpdateTitle" width="500">
            <el-form :model="specialty">
                <el-form-item label="咨询师擅长领域编号" label-width="120px">
                    <el-input v-model="specialty.id" placeholder="请输入擅长领域编号" disabled></el-input>
                </el-form-item>
                <el-form-item label="擅长领域名" label-width="120px">
                    <el-input v-model="specialty.name" placeholder="请输入擅长领域名称"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="close">取消</el-button>
                    <el-button type="primary" @click="saveOrUpdate">
                        {{saveOrUpdateTitle}}
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 分页 -->
        <el-pagination
            style="margin-top: 20px"
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[1, 4, 8, 10]"
            size="default"
            :background="false"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 表格数据
const tableData = ref([]);
// 数据总数
const total = ref(0);
// 当前页码
const pageNum = ref(1);
// 每页显示数量
const pageSize = ref(9);
// 保存或更新弹窗的显示状态
const saveOrUpdateVisiable = ref(false);
// 保存或更新弹窗的标题
const saveOrUpdateTitle = ref("添加");
// 选中的行数据
const selectedRows = ref([]);

// 搜索信息
const SelectedInfo = ref({
    pageNum: '1',
    pageSize: '8',
    name: '',
});

// 初始化时获取擅长领域数据
onMounted(() => {
    getSpecialty();
});

// 获取擅长领域数据
const getSpecialty = () => {
    axios.get('/specialty/list', { params: SelectedInfo.value })
      .then(res => {
            const result = res.data;
            if (result.code === 1) {
                total.value = result.data.total;
                tableData.value = result.data.list;
            } else {
                console.log("获取擅长领域失败");
            }
        });
};

// 处理分页大小变化
const handleSizeChange = (val) => {
    SelectedInfo.value.pageSize = val;
    SelectedInfo.value.pageNum = 1;
    getSpecialty();
};

// 处理当前页码变化
const handleCurrentChange = (val) => {
    SelectedInfo.value.pageNum = val;
    getSpecialty();
};

// 删除逻辑
const deleteData = (url, message) => {
    axios.delete(url)
      .then(resp => {
            const result = resp.data;
            if (result.code === 1) {
                getSpecialty();
                ElMessage({
                    message: message,
                    type: 'success',
                });
            } else {
                ElMessage({
                    message: '删除失败！',
                    type: 'warning',
                });
            }
        })
      .catch(error => {
            ElMessage.error("请求异常");
        });
};

// 删除单个数据
const onDel = (id) => {
    ElMessageBox.confirm(
        '真的要删除吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
      .then(() => {
            deleteData(`/specialty/${id}`, '删除成功！');
        });
};

// 待保存或更新的擅长领域数据
const specialty = ref({
    id: '',
    name: ''
});

// 进入修改页面
const toEdit = (row) => {
    saveOrUpdateVisiable.value = true;
    saveOrUpdateTitle.value = "修改";
    specialty.value = row;
};

// 进入添加页面
const toAdd = () => {
    saveOrUpdateVisiable.value = true;
    saveOrUpdateTitle.value = "添加";
    specialty.value = {
        id: '',
        name: ''
    };
};

// 关闭保存或更新弹窗
const close = () => {
    saveOrUpdateVisiable.value = false;
    specialty.value = {
        id: '',
        name: ''
    };
};

// 保存或更新数据
const saveOrUpdate = () => {
    if (!specialty.value.name?.trim()) {
        ElMessage.error("擅长领域不能为空");
        return;
    }
    if (saveOrUpdateTitle.value === "添加") {
        axios.post('specialty', specialty.value)
          .then(resp => {
                const result = resp.data;
                if (result.code === 1) {
                    pageNum.value = 1;
                    SelectedInfo.value.pageNum = 1;
                    getSpecialty();
                    saveOrUpdateVisiable.value = false;
                } else {
                    console.log("添加领域失败");
                    saveOrUpdateVisiable.value = false;
                }
            })
          .catch(error => {
                ElMessage.error("请求异常");
            });
    } else {
        axios.put('/specialty', specialty.value)
          .then(resp => {
                const result = resp.data;
                if (result.code === 1) {
                    pageNum.value = 1;
                    SelectedInfo.value.pageNum = 1;
                    getSpecialty();
                    saveOrUpdateVisiable.value = false;
                } else {
                    console.log("修改擅长领域失败");
                    saveOrUpdateVisiable.value = false;
                }
            });
        close();
    }
};

// 处理选中行变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection;
};

// 批量删除数据
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的领域名称');
        return;
    }
    ElMessageBox.confirm(
        '确认删除选中的该领域吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
      .then(() => {
            const ids = selectedRows.value.map(row => row.id);
            axios.delete('/specialty/batch', { data: ids })
              .then(res => {
                    const result = res.data;
                    if (result.code === 1) {
                        ElMessage.success('批量删除成功');
                        getSpecialty();
                    } else {
                        ElMessage.error('批量删除失败');
                    }
                })
              .catch(err => {
                    console.error('批量删除失败:', err);
                    ElMessage.error('批量删除失败');
                });
        });
};
</script>

<style scoped>

</style>    